package com.oopnet.template.test.algorithm;

import org.junit.Test;

public class SortAlgorithm {
	/**
	 * 冒泡排序
	 * 
	 * @param array
	 * @return
	 */
	public static int[] bubble(int[] array) {
		if (array.length == 0 || array.length == 1)
			return array;

		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array.length - i - 1; j++) {
				if (array[j] > array[j + 1]) {
					int temp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = temp;
				}
			}
		}
		return array;
	}

	/**
	 * 插入排序
	 * 
	 * @param array
	 * @return
	 */
	public static int[] selectedSort(int[] array) {
		if (array.length == 0 || array.length == 1)
			return array;
		int size = array.length;
		int flag = 0;
		for (int i = 0; i < size - 1; i++) {
			flag = i;
			for (int j = i + 1; j < size; j++) {
				if (array[flag] > array[j])
					flag = j;
			}
			int temp = array[i];
			array[i] = array[flag];
			array[flag] = temp;

		}
		return array;
	}

	public static int[] insertSort(int[] array) {
		if (array.length == 0 || array.length == 1)
			return array;
		int size = array.length;
		int flag = 0;
		int temp = 0;
		for (int i = 1; i < size; i++) {
			flag = i;
			temp=array[i];
			for (int j = i - 1; j >= 0&&temp < array[j]; j--) {
					flag = j;
					array[j+1] = array[j];
			}
			array[flag] = temp;
		}
		return array;
	}

	int[] array = { 18, 5, 2, 4, 6, 7 ,1 ,9 ,30,25,33,20,10,8,8 ,1};

	@Test
	public void testSort() throws Exception {
		array = selectedSort(array);
		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i]);
			System.out.print(", ");
		}
	}
}
